import { BadRequestException, ValidationError, ValidationPipe } from '@nestjs/common'
import { ConfigService } from '@nestjs/config'
import { NestFactory, Reflector } from '@nestjs/core'
import { AppModule } from './app.module'
import { HttpExceptionFilter } from './config/filter/HttpExceptionFilter'
import { TransformInterceptor } from './config/interceptor/TransformInterceptor'
import { ConfigurationKeys } from './config/resources'

async function bootstrap() {
  const app = await NestFactory.create(AppModule)

  app.enableCors()
  app.useGlobalFilters(new HttpExceptionFilter())
  app.useGlobalInterceptors(new TransformInterceptor(new Reflector()))
  app.useGlobalPipes(new ValidationPipe({
    transform: true, whitelist: true, forbidNonWhitelisted: true,
    exceptionFactory: (errors: ValidationError[]) => {
      return new BadRequestException(Object.values(errors[0].constraints)[0])
    }
  }))

  const config = app.get(ConfigService<ConfigurationKeys>)
  const PORT = config.get('server.port')

  await app.listen(PORT, () => {
    console.log(`http://localhost:${PORT}`)
  })
}

bootstrap()
